package com.downguys.tool.thread.pool;

import com.downguys.tool.thread.ExecutorFactory;
import com.downguys.tool.thread.NamedThreadFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author mingmin.zhou(弄死熊猫)
 * @mail 714387891@qq.com
 * @date 2016/12/30
 */
public class ThreadPoolManager {

    public static final ThreadPoolManager I = new ThreadPoolManager();
    private final ExecutorFactory executorFactory = new DefaultExecutorFactory();
    private final NamedThreadFactory threadFactory = new NamedThreadFactory();

    private Executor eventBusExecutor;

    public final Thread newThread(String name, Runnable target) {
        return threadFactory.newThread(name, target);
    }

    public Executor getEventBusExecutor() {
        if (eventBusExecutor == null) {
            synchronized (this) {
                eventBusExecutor = executorFactory.get(ExecutorFactory.EVENT_BUS);
            }
        }
        return eventBusExecutor;
    }

    public static Map<String, Object> getPoolInfo(ThreadPoolExecutor executor) {
        Map<String, Object> info = new HashMap<>();
        info.put("corePoolSize", executor.getCorePoolSize());
        info.put("maxPoolSize", executor.getMaximumPoolSize());
        info.put("activeCount(workingThread)", executor.getActiveCount());
        info.put("poolSize(workThread)", executor.getPoolSize());
        info.put("queueSize(blockedTask)", executor.getQueue().size());
        return info;
    }

}
